//
//  EditController.swift
//  CreateMyCode
//
//  Created by zhibao on 2024/2/20.
//

import UIKit
class EditCodeController: SecSuperController {
    var editDic = [String:Any]()
    var gongnengBtns = [UIButton]()
    
    //选择模版
    var selectTemplateView:SelectMDDMoreScrollView!
    
    //选择颜色
    var selectColorView:SelectCMMoreScrollView!
    
    //选择点阵
    var selectDianZhenView:SelectMDDMoreScrollView!
    
    //选择码眼
    var selectMaYanView:SelectCMMoreScrollView!
    
    //选择图标
    var selectTuBiaoView:SelectMDDMoreScrollView!
    
    //选择文本
    var selectTextView:SelectTextMoreScrollView!
    
    var QRImgView = UIImageView()
    
    var QRDic = [String:Any]()
    var updateDic = [String:Any]()
    var iniQRDic = [String:Any]()
    var iniqrUrl = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.gk_navTitle = LocalizedString("编辑")
        if editDic["custom_parameters_str"] != nil {
            self.QRDic = Helper.dictionary(withJsonString: editDic["custom_parameters_str"] as! String) as? [String:Any] ?? [String:Any]()
        }else{
            self.QRDic = Helper.dictionary(withJsonString: editDic["customParameterStr"] as! String) as? [String:Any] ?? [String:Any]()
        }
        
        self.updateDic = editDic
        self.updateDic["customParameterStr"] = Helper.convert(toJSONData: self.QRDic)
        DLog(message: "updateDic===\(updateDic)")
        self.iniqrUrl = self.updateDic["url"] as! String
        self.iniQRDic = self.QRDic
        
        let saveBtn = UIButton(type: .custom)
        saveBtn.frame = CGRect(x: 0, y: 0, width: 60, height: 40)
        saveBtn.setTitle(LocalizedString("存储"), for: .normal)
        saveBtn.setTitleColor(MYBlue, for: .normal)
        saveBtn.titleLabel?.font = MY_SCALE_SemiboldFONT(14)
        saveBtn.addTarget(self, action: #selector(navClick), for: .touchUpInside)
        
        let item = UIBarButtonItem(customView: saveBtn)
        self.gk_navRightBarButtonItems = [item]
        self.initView()
    }
    
    fileprivate func initView(){
        self.view.addSubview(QRImgView)
        QRImgView.snp.makeConstraints { make in
            make.width.height.equalTo(240)
            make.centerX.equalTo(self.view)
            make.centerY.equalTo(self.view).offset(pixw(p: 30))
        }
        
        let imgUrl = editDic["url"]
        self.gengxinQRImg(imgUrl: imgUrl as! String)
        
        let leftArray:[[String:String]] = [
            ["title":LocalizedString("模版"),"img":"thermometer.transmission"],
            ["title":LocalizedString("颜色"),"img":"coloncurrencysign.circle"],
            ["title":LocalizedString("点阵"),"img":"indianrupeesign.arrow.circlepath"],
            ["title":LocalizedString("码眼"),"img":"mappin.circle"],
            ["title":LocalizedString("图标"),"img":"books.vertical.circle"],
            ["title":LocalizedString("文本"),"img":"thermometer.sun.circle"],
        ]
        
        let btnWidth = (SCREEN_WIDTH - 80 ) / 3
        for i in 0 ..< 2 {
            for j in 0 ..< 3 {
                let btn = UIButton(type: .custom)
                btn.setImage(UIImage(systemName: leftArray[i * 3 + j]["img"] ?? "",withConfiguration: UIImage.SymbolConfiguration(pointSize: 30)), for: .normal)
                btn.tintColor = MYOrange
                btn.backgroundColor = MYColor.color(withHexString: "#E04148", alpha: 0.7)
                
                btn.frame = CGRect(x: 20 + (btnWidth + 20) * CGFloat(j), y: navigationFullHeight() + 10 + (80 + 10) * CGFloat(i), width: btnWidth, height: 80)
                btn.tag = 100 + i * 3 + j
                
                if btn.tag == 100 {
                    btn.backgroundColor = MYColor.color(withHexString: "#E04148", alpha: 0.7)
                }else{
                    btn.backgroundColor = MYColor.color(withHexString: "#2666e4", alpha: 0.7)
                }
                btn.layer.cornerRadius = pixw(p: 5)
                btn.setTitle(leftArray[i * 3 + j]["title"], for: .normal)
                btn.setTitleColor(UIColor.white, for: .normal)
                btn.titleLabel?.font = MY_SCALE_SemiboldFONT(14)
                btn.titleLabel?.numberOfLines = 0
                btn.titleLabel?.textAlignment = .center
                btn.titleLabel?.lineBreakMode = .byWordWrapping
                btn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
                btn.setButtonImageAlignmentStyle(.top, imageAndLabelSpace: pixw(p: 3))
                self.view.addSubview(btn)
                gongnengBtns.append(btn)
            }
        }
        
        //模版
        self.selectTemplateView = SelectMDDMoreScrollView(frame: CGRect(x: 0, y: SCREEN_HEIGHT - pixw(p: 139) - safeDistanceBottom(), width: SCREEN_WIDTH, height: pixw(p: 139) + safeDistanceBottom()),type: .edit)
        self.selectTemplateView.selectBlock = {
            dic in
            let value = dic["value"] as? String ?? ""
            if  value == CLEARFLAG {
                self.gengxinQRImg(imgUrl: self.iniqrUrl)
                self.QRDic = self.iniQRDic
                self.updateDic["url"] = self.iniqrUrl
                self.updateDic["customParameterStr"] = Helper.convert(toJSONData: self.QRDic)
            }else{
                let nav = self.QRDic["nav"] as? String ?? ""
                self.QRDic = dic["default_parameters"] as! [String : Any]
                
                let qrCode = self.iniQRDic["qrCode"] as? [String:Any] ?? [String:Any]()
                let text = qrCode["text"] as? String ?? ""
                if text != "" {
                    var qrCode = self.QRDic["qrCode"] as! [String:Any]
                    let iniQrCode = self.iniQRDic["qrCode"] as! [String:Any]
                    qrCode["text"] = iniQrCode["text"]
                    self.QRDic["qrCode"] = qrCode
                }
                self.QRDic["type"] = dic["type"]
                if nav != "" {
                    self.QRDic["nav"] = nav
                }
                
                if (dic["type"] as! NSNumber).stringValue == "0" {
                    self.updateDic["url"] = dic["demo_url"]
                    self.updateDic["customParameterStr"] = Helper.convert(toJSONData: self.QRDic)
                    self.gengxinQRImg(imgUrl: dic["demo_url"] as! String)
                }else{
                    self.getNewQring { imgUrl in
                        self.updateDic["url"] = imgUrl
                        self.updateDic["customParameterStr"] = Helper.convert(toJSONData: self.QRDic)
                    }
                }
            }
        }
        
        self.selectTemplateView.dealBlock = {
            flag in
            
            UIView.animate(withDuration: 0.3) {
                self.selectTemplateView.top = SCREEN_HEIGHT
            }
        }
        self.view.addSubview(selectTemplateView)
        
        //颜色
        self.selectColorView = SelectCMMoreScrollView(frame: CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: pixw(p: 180) + safeDistanceBottom()), type: .color)
        self.selectColorView.selectBlock = {
            dic in
            let value = dic["value"] as? String ?? ""
            if  value == CLEARFLAG {
                var qrCode = self.QRDic["qrCode"] as! [String:Any]
                let iniQrCode = self.iniQRDic["qrCode"] as! [String:Any]
                if dic["type"] as! String == LocalizedString("背景色") {
                    let backgroundColor = iniQrCode["backgroundColor"] as? String ?? ""
                    if backgroundColor == "" {
                        qrCode.removeValue(forKey: "backgroundColor")
                    }else{
                        qrCode["backgroundColor"] = iniQrCode["backgroundColor"]
                    }
                }else{
                    let colorDark = iniQrCode["colorDark"] as? String ?? ""
                    if colorDark == "" {
                        qrCode.removeValue(forKey: "colorDark")
                    }else{
                        qrCode["colorDark"] = iniQrCode["colorDark"]
                    }
                }
                self.QRDic["qrCode"] = qrCode
            }else{
                var qrCode = self.QRDic["qrCode"] as! [String:Any]
                if dic["type"] as! String == LocalizedString("背景色") {
                    qrCode["backgroundColor"] = dic["value"]
                }else{
                    qrCode["colorDark"] = dic["value"]
                }
                self.QRDic["qrCode"] = qrCode
                DLog(message: "\(dic["value"]!)    \(self.QRDic["qrCode"]!)")
            }
            self.getNewQring { imgUrl in
                self.updateDic["url"] = imgUrl
                self.updateDic["customParameterStr"] = Helper.convert(toJSONData: self.QRDic)
            }
        }
        self.selectColorView.dealBlock = {
            flag in
            UIView.animate(withDuration: 0.3) {
                self.selectColorView.top = SCREEN_HEIGHT
            }
        }
        self.view.addSubview(self.selectColorView)
        
        //点阵
        self.selectDianZhenView = SelectMDDMoreScrollView(frame: CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: pixw(p: 139) + safeDistanceBottom()), type: .dianzhen)
        self.selectDianZhenView.selectBlock = {
            dic  in
            let value = dic["value"] as? String ?? ""
            var qrCode = self.QRDic["qrCode"] as! [String:Any]
            let iniQrCode = self.iniQRDic["qrCode"] as! [String:Any]
            let qrData = qrCode["qrData"] as? String ?? ""
            if  value == CLEARFLAG {
                if qrData != "" {
                    qrCode["qrData"] = iniQrCode["qrData"]
                }else{
                    qrCode.removeValue(forKey: "qrData")
                }
            }else{
                qrCode["qrData"] = dic["value"]
            }
            self.QRDic["qrCode"] = qrCode
            self.getNewQring { imgUrl in
                self.updateDic["url"] = imgUrl
                self.updateDic["customParameterStr"] = Helper.convert(toJSONData: self.QRDic)
            }
        }
        self.selectDianZhenView.dealBlock = {
            flag in
            UIView.animate(withDuration: 0.3) {
                self.selectDianZhenView.top = SCREEN_HEIGHT
            }
        }
        self.view.addSubview(self.selectDianZhenView)
        
        //码眼
        self.selectMaYanView = SelectCMMoreScrollView(frame: CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: pixw(p: 250) + safeDistanceBottom()), type: .mayan)
        self.selectMaYanView.selectBlock = {
            dic in
            let value = dic["value"] as? String ?? ""
            if  value == CLEARFLAG {
                var qrCode = self.QRDic["qrCode"] as! [String:Any]
                let iniQrCode = self.iniQRDic["qrCode"] as! [String:Any]
                if dic["type"] as! String == LocalizedString("外框") {
                    let eye_outer = iniQrCode["eye_outer"] as? String ?? ""
                    if eye_outer == "" {
                        qrCode.removeValue(forKey: "eye_outer")
                    }else{
                        qrCode["eye_outer"] = iniQrCode["eye_outer"]
                    }
                }else{
                    let eye_inner = iniQrCode["eye_inner"] as? String ?? ""
                    if eye_inner == "" {
                        qrCode.removeValue(forKey: "eye_inner")
                    }else{
                        qrCode["eye_inner"] = iniQrCode["eye_inner"]
                    }
                }
                self.QRDic["qrCode"] = qrCode
            }else{
                var qrCode = self.QRDic["qrCode"] as! [String:Any]
                if dic["type"] as! String == LocalizedString("外框") {
                    qrCode["eye_outer"] = dic["value"]
                }else{
                    qrCode["eye_inner"] = dic["value"]
                }
                self.QRDic["qrCode"] = qrCode
            }
            self.getNewQring { imgUrl in
                self.updateDic["url"] = imgUrl
                self.updateDic["customParameterStr"] = Helper.convert(toJSONData: self.QRDic)
            }
        }
        self.selectMaYanView.dealBlock = {
            flag in
            UIView.animate(withDuration: 0.3) {
                self.selectMaYanView.top = SCREEN_HEIGHT
            }
        }
        self.view.addSubview(self.selectMaYanView)
        
        //图标
        self.selectTuBiaoView = SelectMDDMoreScrollView(frame: CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: pixw(p: 139) + safeDistanceBottom()), type: .tubiao)
        self.selectTuBiaoView.selectBlock = {
            dic  in
            let value = dic["value"] as? String ?? ""
            var qrCode = self.QRDic["qrCode"] as! [String:Any]
            let iniQrCode = self.iniQRDic["qrCode"] as! [String:Any]
            let logo = iniQrCode["logo"] as? String ?? ""
            if  value == CLEARFLAG {
                if logo != "" {
                    qrCode["logo"] = iniQrCode["logo"]
                }else{
                    qrCode.removeValue(forKey: "logo")
                }
                self.QRDic["qrCode"] = qrCode
                self.getNewQring { imgUrl in
                    self.updateDic["url"] = imgUrl
                    self.updateDic["customParameterStr"] = Helper.convert(toJSONData: self.QRDic)
                }
            }else if value == ADDFLAG {
                self.selectPic()
            }else{
                qrCode["logo"] = dic["value"]
                self.QRDic["qrCode"] = qrCode
                self.getNewQring { imgUrl in
                    self.updateDic["url"] = imgUrl
                    self.updateDic["customParameterStr"] = Helper.convert(toJSONData: self.QRDic)
                }
            }
        }
        self.selectTuBiaoView.dealBlock = {
            flag in
            UIView.animate(withDuration: 0.3) {
                self.selectTuBiaoView.top = SCREEN_HEIGHT
            }
        }
        self.view.addSubview(selectTuBiaoView)
        
        //文本
        self.selectTextView = SelectTextMoreScrollView(frame: CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: pixw(p: 200) + safeDistanceBottom()))
        self.selectTextView.selectMoreBlock = {
            dic  in
            let value = dic["value"] as? String ?? ""
            var qrCode = self.QRDic["qrCode"] as! [String:Any]
            let iniQrCode = self.iniQRDic["qrCode"] as! [String:Any]
            let frame = iniQrCode["frame"] as? String ?? ""
            let frameText = iniQrCode["frameText"] as? String ?? ""
            let frameColor = iniQrCode["frameColor"] as? String ?? ""
            if  value == CLEARFLAG {
                if frame != "" {
                    qrCode["frame"] = iniQrCode["frame"]
                }else{
                    qrCode.removeValue(forKey: "frame")
                }
                
                if frameText != "" {
                    qrCode["frameText"] = iniQrCode["frameText"]
                }else{
                    qrCode.removeValue(forKey: "frameText")
                }
                
                if frameColor != "" {
                    qrCode["frameColor"] = iniQrCode["frameColor"]
                }else{
                    qrCode.removeValue(forKey: "frameColor")
                }
            }else{
                qrCode["frame"] = "1"
                qrCode["frameText"] = dic["text"]
                qrCode["frameColor"] = dic["value"]
            }
            self.QRDic["qrCode"] = qrCode
            self.getNewQring { imgUrl in
                self.updateDic["url"] = imgUrl
                self.updateDic["customParameterStr"] = Helper.convert(toJSONData: self.QRDic)
            }
        }
        self.selectTextView.dealMoreBlock = {
            flag,text in
            UIView.animate(withDuration: 0.3) {
                self.selectTextView.top = SCREEN_HEIGHT
            }
        }
        self.view.addSubview(self.selectTextView)
    }
    
    @objc fileprivate func navClick(){
        if !UserInfoManager.shared().isVip(){
            Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("开通该会员才能保存哦！"), withSureBtnTitle: LocalizedString("开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                if index == 1 {
                    let controller = PayMarkController()
                    self.navigationController?.pushViewController(controller, animated: true)
                }
            }
          return
        }
        self.updateDateToAF { dic in
            let controller = FileDetailController()
            controller.dic = self.updateDic
            self.navigationController?.pushViewController(controller, animated: true)
        }
    }
    
    fileprivate func updateDateToAF(result:@escaping (_ dic: [String:Any]) -> Void){
        QMUITips.showLoading(LocalizedString("...保存中..."), detailText: LocalizedString("...压缩保存中..."), in: self.view)
        let put = OSSPutObjectRequest()
        put.bucketName = "wyqrcode"
        let fileName = "qrcode/\(arc4random() % 10000)\(arc4random() % 10000).png"
        put.objectKey = fileName
        put.uploadingData = QRImgView.image!.pngData()!
        put.uploadProgress = {
            bytesSent,totalByteSent,totalBytesExpectedToSend in
            DLog(message: "\(bytesSent)  \(totalByteSent)   \(totalBytesExpectedToSend)")
        }
        
        let putTask = MYGlobal.share().client.putObject(put)
        putTask.continue(successBlock: { task in
            if task.error == nil {
                DispatchQueue.main.async {
                    QMUITips.hideAllTips()
                    self.updateDic["url"] = "http://qrcode.oss.xinmengma.com/\(fileName)"
                    HttpHelper.sharedInstance().sendPost("api/qrcode", parameters: self.updateDic) { operation, responseObject1 in
                        QMUITips.showSucceed(LocalizedString("保存成功"), detailText: LocalizedString("已保存！"))
                        result(responseObject1.data as? [String : Any] ?? [String : Any]())
                    } failure: { operation, error in
                        
                    }

                  }
            }else{
                DLog(message: "upload object failed, error: \(task.error.debugDescription)")
            }
            return nil
        })
    }
    
    fileprivate func gengxinQRImg(imgUrl:String){
        let imgUrl1 = imgUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        self.QRImgView.yy_setImage(with: URL(string: imgUrl1!), placeholder: nil,options: .showNetworkActivity) { image, url, from, stage, error in
            self.QRImgView.snp.updateConstraints { make in
                let width = image!.size.width
                let height = image!.size.height
                if width == height {
                    make.width.height.equalTo(250)
                }else if width < height {
                    make.width.equalTo(240)
                    let height = 240 * image!.size.height / image!.size.width;
                    make.height.equalTo(height)
                }else if width > height {
                    make.width.equalTo(345)
                    let height = 345 * image!.size.height / image!.size.width
                    make.height.equalTo(height)
                }
            }
        }
    }
    
    @objc fileprivate func btnClick(sender:UIButton){
        selectTemplateView.top = SCREEN_HEIGHT
        selectColorView.top = SCREEN_HEIGHT
        selectDianZhenView.top = SCREEN_HEIGHT
        selectMaYanView.top = SCREEN_HEIGHT
        selectTuBiaoView.top = SCREEN_HEIGHT
        selectTextView.top = SCREEN_HEIGHT
        if sender.tag == 100 {
            UIView.animate(withDuration: 0.3) {
                self.selectTemplateView.top = SCREEN_HEIGHT - pixw(p: 139) - safeDistanceBottom()
            }
        }else if sender.tag == 101 {
            UIView.animate(withDuration: 0.3) {
                self.selectColorView.top = SCREEN_HEIGHT - pixw(p: 180) - safeDistanceBottom()
            }
        }else if sender.tag == 102 {
            UIView.animate(withDuration: 0.3) {
                self.selectDianZhenView.top = SCREEN_HEIGHT - pixw(p: 139) - safeDistanceBottom()
            }
        }else if sender.tag == 103 {
            UIView.animate(withDuration: 0.3) {
                self.selectMaYanView.top = SCREEN_HEIGHT - pixw(p: 250) - safeDistanceBottom()
            }
        }else if sender.tag == 104 {
            UIView.animate(withDuration: 0.3) {
                self.selectTuBiaoView.top = SCREEN_HEIGHT - pixw(p: 139) - safeDistanceBottom()
            }
        }else if sender.tag == 105 {
            UIView.animate(withDuration: 0.3) {
                self.selectTextView.top = SCREEN_HEIGHT - pixw(p: 200) - safeDistanceBottom()
            }
        }
        
        for btn in gongnengBtns {
            btn.backgroundColor = MYColor.color(withHexString: "#2666e4", alpha: 0.7)
        }
        sender.backgroundColor = MYColor.color(withHexString: "#E04148", alpha: 0.7)
        
    }
    
    fileprivate func getNewQring(result:@escaping (_ imgUrl: String) -> Void){
        QRNetHelper.sharedInstance().sendPost("qrcodes/qr2", parameters: self.QRDic["qrCode"] as! [AnyHashable : Any] ) { operation, responseObject in
            let repData1 = responseObject.data as! [String:Any]
            //DLog(message: "eeee===\(repData1)")
            self.gengxinQRImg(imgUrl: repData1["url"] as! String)
            result(repData1["url"] as! String)
        } failure: { operation, error in
            
        }
    }
    
    fileprivate func selectPic(){
        let authStatus = PHPhotoLibrary.authorizationStatus()
        if authStatus == .notDetermined {
            PHPhotoLibrary.requestAuthorization { status in
                if status == .authorized {
                    DispatchQueue.main.async {
                        self.oprea()
                        }
                }else{
                    QMUITips.showInfo(LocalizedString("无相册权限，请到“设置”中开启相册权限"))
                }
            }
        }else{
            self.oprea()
        }
    }
    
    fileprivate func oprea(){
       let imagePickerVc = TZImagePickerController(maxImagesCount: 1, delegate: nil)
        imagePickerVc?.naviBgColor = MYBlock
        imagePickerVc?.naviTitleColor = UIColor.white
        imagePickerVc?.barItemTextColor = UIColor.white
        imagePickerVc?.statusBarStyle = .lightContent;
        imagePickerVc?.allowPickingVideo = false
        imagePickerVc?.allowTakePicture = false
        imagePickerVc?.allowTakeVideo = false
        imagePickerVc?.modalPresentationStyle = .fullScreen
        imagePickerVc?.didFinishPickingPhotosHandle = {
            photos,assets,isSelectOriginalPhoto in
            self.updataLogo(logoImg: photos!.first ?? UIImage())
        }
        self.present(imagePickerVc!, animated: true)
    }
    
    fileprivate  func updataLogo(logoImg:UIImage){
        QMUITips.showLoading(LocalizedString("...上传中..."), detailText: LocalizedString("...压缩上传中..."), in: self.view)
        let put = OSSPutObjectRequest()
        put.bucketName = "wyqrcode"
        let fileName = "logo/\(arc4random() % 10000)\(arc4random() % 10000).png"
        put.objectKey = fileName
        put.uploadingData = logoImg.pngData()!
        put.uploadProgress = {
            bytesSent,totalByteSent,totalBytesExpectedToSend in
            DLog(message: "\(bytesSent)  \(totalByteSent)   \(totalBytesExpectedToSend)")
        }
        
        let putTask = MYGlobal.share().client.putObject(put)
        putTask.continue(successBlock: { task in
            if task.error == nil {
                
                DispatchQueue.main.async {
                    QMUITips.hideAllTips()
                    var qrCode = self.QRDic["qrCode"] as! [String:Any]
                    qrCode["logo"] = "http://qrcode.oss.xinmengma.com/\(fileName)"
                    self.QRDic["qrCode"] = qrCode
                    self.getNewQring { imgUrl in
                        self.updateDic["url"] = imgUrl
                        self.updateDic["customParameterStr"] = Helper.convert(toJSONData: self.QRDic)
                    }
                  }
            }else{
                DLog(message: "upload object failed, error: \(task.error.debugDescription)")
            }
            return nil
        })
    }
}
